"""Image utility helpers."""

from __future__ import annotations

import numpy as np

from ..qt_compat import cv2


def to_display(image: np.ndarray) -> np.ndarray:
    if image.ndim == 2:
        data = image
        if data.dtype != np.uint8:
            data = cv2.normalize(data, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
        return cv2.cvtColor(data, cv2.COLOR_GRAY2BGR)

    data = image
    if data.dtype != np.uint8:
        data = cv2.normalize(data, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
    if data.shape[2] == 3:
        return data
    if data.shape[2] == 4:
        return cv2.cvtColor(data, cv2.COLOR_BGRA2BGR)
    # Fallback: convert to grayscale and back to 3 channels
    gray = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)
    return cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)


def ensure_gray(image: np.ndarray) -> np.ndarray:
    if image.ndim == 2:
        return image.astype(np.float32)
    return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY).astype(np.float32)


def make_odd(value: int) -> int:
    return value if value % 2 else value + 1
